package org.particlethink.auth;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.List;
import java.util.regex.Pattern;

@Component
public class CustomizedFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

	private static final String err_path = ".*/error";
	private static final String webjar_path = ".*/webjar/.*";

	private static final Pattern err_pattern = Pattern.compile(err_path);
	private static final Pattern webjar_pattern = Pattern.compile(webjar_path);

	private CustomizedUserProperties customizedUserProperties;

	@Autowired
	public void setCustomizedUserProperties(CustomizedUserProperties customizedUserProperties) {
		this.customizedUserProperties = customizedUserProperties;
	}

	@Override
	public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
//        return null;
		FilterInvocation invocation = (FilterInvocation) o;
		String requestUrl = invocation.getRequestUrl();
		if (err_pattern.matcher(requestUrl).find() || webjar_pattern.matcher(requestUrl).find()) {
			return null;
		}
		List<String> withOutAuthentication = customizedUserProperties.getWithOutAuthentication();
		if (withOutAuthentication != null && withOutAuthentication.size() > 0) {
			for (String s : withOutAuthentication) {
				if (Pattern.matches(Pattern.quote(s), requestUrl)) {
					return null;
				}
			}
		}
		return SecurityConfig.createList(requestUrl);
	}

	@Override
	public Collection<ConfigAttribute> getAllConfigAttributes() {
		return null;
	}

	@Override
	public boolean supports(Class<?> aClass) {
		return FilterInvocation.class == aClass;
	}
}
